﻿#pragma execution_character_set("utf-8")
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QCoreApplication>

const QString baiduTokenUrl = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%1&client_secret=%2&";


const char *client_id = "ZOmxvLqBUPZMknP6IkCtGs4S";
const char *secret_id = "mtVbwNLA3SBXQkrbscZRl8MESeZrTybp";

const QString baiduImageUrl = "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal?access_token=%1";



MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);




}

MainWindow::~MainWindow()
{
    delete ui;
}




void MainWindow::on_pushButton_clicked()
{
    ui->label_2->setAlignment(Qt::AlignCenter); // 水平+垂直居中
    ui->label_2->setText("正在努力识别图片里的动物哦~");


    QByteArray img = Image::imgToBase64(imgPath);//image = ......
    QByteArray imgData = "image=" + img;//body
    //获取access_token
    QByteArray replyData;//保存回复信息

    QString url = QString(baiduTokenUrl).arg(client_id).arg(secret_id);


    QMap<QString,QString> header;//封装了一个头部信息
    header.insert(QString("Content-Type"),QString("application/x-www-form-urlencoded"));


    QString accessToken;

    bool result = Http::post_sync(url,header,imgData,replyData);
    if(result)
    {
        QJsonObject obj = QJsonDocument::fromJson(replyData).object();
        accessToken = obj.value("access_token").toString();

    }

    replyData.clear();

    QString imgUrl = baiduImageUrl.arg(accessToken);
    result = Http::post_sync(imgUrl,header,imgData,replyData);

    if(result)
    {
        QJsonObject obj = QJsonDocument::fromJson(replyData).object();
        QJsonValue val = obj.value("result");


        /*if(val.isArray())
        {
            QJsonValue fst = val.toArray().at(0);
            QJsonValue snd = val.toArray().at(1);
            QJsonValue thd = val.toArray().at(2);
            if(fst.isObject())
            {
                QString name = fst.toObject().value("name").toString();
                QString score = fst.toObject().value("score").toString();
                ui->lineEdit->setText( "图片里的动物有" +score + "的概率为" +name);
               return;
            }
        }*/




        if(val.isArray())
        {
            QJsonArray arr = val.toArray();
            QString result = "   图片识别结果：\n";
            result += "────────────────\n";

            for(int i = 0; i < qMin(arr.size(), 3); i++)
            {
                QJsonValue item = arr.at(i);
                if(item.isObject())
                {
                    QJsonObject obj = item.toObject();
                    QString name = obj.value("name").toString();
                    QString score = obj.value("score").toString();

                    // 将分数转换为百分比形式
                    double percent = score.toDouble() * 100;
                    result += QString("   %1 : %2 - %3%\n")
                                  .arg(i+1)
                                  .arg(name)
                                  .arg(percent, 0, 'f', 1);
                }
            }
            ui->label_2->setWordWrap(true);  // 启用自动换行

            ui->label_2->setText(result);
            return;
        }

    }
    ui->label_2->setText("无法识别图片里的动物，/n看看是不是图片格式出错了~");
}


void MainWindow::on_pushButton_2_clicked()
{
    imgPath = QFileDialog::getOpenFileName(this, "选择图片", QCoreApplication::applicationDirPath());
    if(imgPath.isEmpty())
    {
        QMessageBox::warning(this, "提示", "还没选图片呢");
        ui->label_2->setText("这次又是什么动物呢~");
    }

    QPixmap pix(imgPath);
    // 缩放图片以适应label，保持纵横比
    QPixmap scaledPix = pix.scaled(ui->label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
    ui->label->setPixmap(scaledPix);
    // 确保label不自动拉伸图片
    ui->label->setScaledContents(false);
}

